package crawler.dazhong;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zql.entity.AgencyEntity;

import dao.AgencyDao;
import util.HttpConnectionGet;
import util.MybatisTool;
import util.TianYanCha;

public class JinKouDaZhong {
	List<AgencyEntity> getAgency() {
		List<AgencyEntity> list = new ArrayList<AgencyEntity>();
		try {
			String dealersData = HttpConnectionGet.getJson("http://openapi.dlp.vwimport.cn/openapi/dealer/dealerlist");
			JSONArray dealers = JSON.parseObject(dealersData).getJSONArray("data");
			for (int i=0;i<dealers.size();i++) {
				JSONObject dealer = dealers.getJSONObject(i);
				if ("1".equals(dealer.getString("id"))) {
					continue;
				}
				String name = dealer.getString("dealerName");
				String address = dealer.getString("address");
				String sellTell = dealer.getString("tel");
				String serviceTell = dealer.getString("customerServiceTel");
				String lng = dealer.getString("lng");
				String lat = dealer.getString("lat");
				String proName = dealer.getString("provinceName");
				String cityName = dealer.getString("cityName");
				JSONArray types = dealer.getJSONArray("types");
				String type = "";
				if(types!=null&&types.size()>0) {
				for (int j=0;j<types.size();j++) {
					type = type+types.getString(j)+"/";
				}
				}else {}
				List<String> shareholder = TianYanCha.getShareholder(name);
				String sControllingShareholder = shareholder.get(0);
				String sOtherShareholders = shareholder.get(1);
				
				AgencyEntity agency = new AgencyEntity();
				agency.setdCloseDate(null);
				agency.setdOpeningDate(null);
				agency.setdUpdateTime(new Timestamp(System.currentTimeMillis()));
				agency.setnBrandID(-1);
				agency.setsBrand("大众");
				agency.setnDealerIDWeb(-1);
				agency.setnManufacturerID(-1);
				agency.setsManufacturer("进口大众");
				agency.setnState(1);
				agency.setsAddress(address);
				agency.setsCity(cityName);
				agency.setsCustomerServiceCall(serviceTell);
				agency.setsDealerName(name);
				agency.setsDealerType(type);
				agency.setsProvince(proName);
				agency.setsSaleCall(sellTell);
				
				agency.setsLongitude(lng);
				agency.setsLatitude(lat);
				agency.setsControllingShareholder(sControllingShareholder);
				agency.setsOtherShareholders(sOtherShareholders);
				
				list.add(agency);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return list;
	}
	public static void main(String[] args) {
		JinKouDaZhong crawler = new JinKouDaZhong();
		System.out.println("爬虫开始...");
		List<AgencyEntity> agencys = crawler.getAgency();
		System.out.println("抓取完毕,正在存库");
		for(AgencyEntity agency : agencys) {
			MybatisTool.save(agency);
		}
		MybatisTool.close();
		System.out.println("请查看数据库");
	}
}
